package cmd

import (
	"fmt"
	"md5util/util"
	"os"
	"path"
	"time"

	"github.com/olekukonko/tablewriter"
	"github.com/spf13/cobra"
)

var md5fileCmd = &cobra.Command{
	Use:   "file",
	Short: "文件MD5",
	Long:  `根据文件路径生成文件MD5字符串`,
	Run: func(cmd *cobra.Command, args []string) {
		upper, _ := cmd.Flags().GetBool("upper")
		table := tablewriter.NewWriter(os.Stdout)
		table.SetHeader([]string{"NAME", "MD5", "SIZE", "SPENT(ms)"})
		defer table.Render()

		for _, file := range args {
			start := time.Now()
			md5str, bsize, err := util.MD5File(file, upper)
			spent := fmt.Sprintf("%d", time.Since(start).Milliseconds())
			if err != nil {
				fmt.Println(err)
			} else {
				table.Append([]string{path.Base(file), md5str, bsize, spent})
			}
		}
	},
}

func init() {
	rootCmd.AddCommand(md5fileCmd)
}
